package cn.wolfcode.web.Interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.util.RequestPermission;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;

public class AuthorityManagement implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拦截动态方法
        if (handler instanceof HandlerMethod){
            Employee employee = (Employee) request.getSession().getAttribute("USER_IN_SESSION");;
            //判断用户是否是管理员
            if (employee.isAdmin()) {
                return true;
            }
            //获取注解上的内容,为空则放行
            HandlerMethod method = (HandlerMethod) handler;
            RequestPermission methodAnnotation = method.getMethodAnnotation(RequestPermission.class);
            if (methodAnnotation==null){
                return true;
            }
            //查询session作用域中所有的用户权限
            List<Permission> permissionList = (List<Permission>) request.getSession().getAttribute("PERMISSION_IN_SESSION");
            for (Permission permission:permissionList){
                String expression = permission.getExpression();
                if (expression.equals(methodAnnotation.expression())){
                    return true;
                }
            }
            //判断请求类型
            ResponseBody responseBody = method.getMethodAnnotation(ResponseBody.class);
            if (responseBody==null){
                response.sendRedirect("/nopermission");
            }else {
                response.setContentType("application/json;charset=utf-8");
                String jsonString = JSON.toJSONString(new JsonResult(false, "没有权限访问"));
                PrintWriter writer = response.getWriter();
                writer.write(jsonString);
            }
            return false;
        }
        return true;
    }
}
